<?php

namespace App\Remote\Feishu\Auth;

use Closure;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Request as RequestAlias;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class UserRemote extends Remote
{

    const TYPE_USER_GET = "open_id";

    /**
     * 获取用户信息
     *
     * @param string $userType
     * @param string $ssoToken
     * @param string $openId
     * @return mixed|void
     * @throws GuzzleException
     */
    public static function userinfoBySsoToken(string $userType, string $ssoToken, string $openId)
    {
        return self::customRequest(
            "/open-apis/contact/v3/users/{$openId}",
            RequestAlias::METHOD_GET,
            [
                "user_id_type" => $userType
            ],
            ["Authorization" => sprintf("Bearer %s", $ssoToken)]
        );
    }

    /**
     * @param string $departmentId
     * @param string $tenantAccessToken
     * @param string $pageToken
     * @return mixed|void
     * @throws GuzzleException|ValidationException
     */
    public static function getUserByDepartment(string $departmentId, string $tenantAccessToken, string $pageToken = "")
    {
        return self::customRequestV3(
            "/open-apis/contact/v3/users/find_by_department?" . http_build_query([
                "department_id_type" => "open_department_id",
                "department_id"      => $departmentId,
                "page_size"          => 50,
                "page_token"         => $pageToken
            ]),
            RequestAlias::METHOD_GET,
            null
            ,
            ["Authorization" => sprintf("Bearer %s", $tenantAccessToken)]
        );
    }


    public static function registerResponseHandle(): Closure
    {
        return function () {
            list($responseHttpCode, $responseContents) = func_get_args();
            if ($responseHttpCode == ResponseAlias::HTTP_OK && isJson($responseContents)) {
                return json_decode($responseContents, JSON_UNESCAPED_UNICODE)["data"];
            }
            throw new \Exception("飞书远程请求失败");
        }; // TODO: Change the autogenerated stub
    }
}
